import { defineStore } from 'pinia'
import { store } from '../index'

import elementPlusZhCn from 'element-plus/es/locale/lang/zh-cn'
import elementPlusEn from 'element-plus/es/locale/lang/en'
import elementPlusZhTw from 'element-plus/es/locale/lang/zh-tw'

import dayjsZhCn from 'dayjs/locale/zh-cn'
import dayjsEn from 'dayjs/locale/en'
import dayjsZhTw from 'dayjs/locale/zh-tw'

import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import type { LocaleDropdownType } from '@/types/locale'

const { wsLocal } = useCache()

// element-plus 国际化映射
const elLocaleMap = {
  'zh-CN': elementPlusZhCn,
  'zh-TW': elementPlusZhTw,
  en: elementPlusEn
}

// markdown 国际化映射
const markdownLocaleMap = {
  'zh-CN': 'zh_CN',
  'zh-TW': 'zh_TW',
  en: 'en_US'
}

// tinymce 国际化映射
const tinymceLocaleMap = {
  'zh-CN': 'zh_CN',
  'zh-TW': 'zh_TW',
  en: 'en'
}

// dayjs 国际化映射
const dayjsLocaleMap = {
  'zh-CN': dayjsZhCn,
  'zh-TW': dayjsZhTw,
  en: dayjsEn
}

export const useLocaleStore = defineStore('locale', () => {
  const currentLocale = ref({
    lang: wsLocal.getItem(CACHE_KEY.SYSTEM_LOCALE) || 'zh-CN',
    elLocale: elLocaleMap[wsLocal.getItem(CACHE_KEY.SYSTEM_LOCALE) || 'zh-CN'],
    markdownLocale: markdownLocaleMap[wsLocal.getItem(CACHE_KEY.SYSTEM_LOCALE) || 'zh-CN'],
    tinymceLocale: tinymceLocaleMap[wsLocal.getItem(CACHE_KEY.SYSTEM_LOCALE) || 'zh-CN'],
    dayjsLocale: dayjsLocaleMap[wsLocal.getItem(CACHE_KEY.SYSTEM_LOCALE) || 'zh-CN']
  })
  const localeMap = ref([
    { lang: 'zh-CN', name: '简体中文' },
    { lang: 'zh-TW', name: '繁體中文' },
    { lang: 'en', name: 'English' }
  ])

  const setCurrentLocale = (localeMap: LocaleDropdownType) => {
    currentLocale.value.lang = localeMap?.lang
    currentLocale.value.elLocale = elLocaleMap[localeMap?.lang]
    currentLocale.value.markdownLocale = markdownLocaleMap[localeMap?.lang]
    wsLocal.setItem(CACHE_KEY.SYSTEM_LOCALE, localeMap?.lang)
  }

  const getCurrentLocale = () => {
    return currentLocale.value
  }

  const getLocaleMap = () => {
    return localeMap.value
  }

  return {
    currentLocale,
    localeMap,
    setCurrentLocale,
    getCurrentLocale,
    getLocaleMap
  }
})

export const useLocaleStoreWithOut = () => {
  return useLocaleStore(store)
}
